package com.gillion.dao;

import java.sql.*;

/**
 * Created by admin on 2016/11/1.
 */
public class UntilDao {
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    private static final String URL = "jdbc:mysql://172.16.0.142:3306/gillion_test";
    private static final String USERNAME = "root";
    private static final String PASSWORD = "root";
    private Connection conn = null;
    private PreparedStatement pst = null;
    private ResultSet rs = null;
    public  Connection getConnection(){
        try {
            Class.forName(DRIVER);
            conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
            } catch (Exception e)
                {    e.printStackTrace();    }
                return conn;
    }

    public ResultSet  Search(String sql, String str[]) {
        getConnection();
        try {
            PreparedStatement pst =conn.prepareStatement(sql);
            if (str != null) {
                for (int i = 0; i < str.length; i++) {
                    pst.setString(i + 1, str[i]);
                }
            }
            rs = pst.executeQuery();

        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return rs;
    }


    public int executeUpdate(String sql, Object... param) {
        conn = getConnection();
        int row = 0;
        try {
            pst = conn.prepareStatement(sql);
            if (param != null) {
                for (int i = 0; i < param.length; i++) {
                    pst.setObject(i + 1, param[i]);
                }
            }
            row = pst.executeUpdate();
        } catch (SQLException e) {     // TODO Auto-generated catch block
          e.printStackTrace();
                 }
                return row;
    }



    public void closeConnection() {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if(rs!=null){
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

